<template>
    <view style="padding: 15px;">
        <u-form ref="validateFormRef" :model="validateForm.value" :label-width="150">
            <u-form-item label="商品规格" prop="goodsSpecificationId" required>
                <u-input type="select" :select-open="validateForm.controls.goodsSpecificationId.isShow"
                         v-model="validateForm.controls.goodsSpecificationId.textDesc"
                         placeholder="请选择商品规格" @click="validateForm.controls.goodsSpecificationId.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>
            <u-form-item label="商品颜色" prop="goodsColorId" required>
                <u-input type="select" :select-open="validateForm.controls.goodsColorId.isShow" v-model="validateForm.controls.goodsColorId.textDesc"
                         placeholder="请选择商品颜色" @click="validateForm.controls.goodsColorId.isShow = true; $forceUpdate();"></u-input>
            </u-form-item>
            <u-form-item label="成本价" prop="costPrice">
                <u-input v-model="validateForm.value.costPrice" placeholder="请输入成本价"/>
            </u-form-item>
            <u-form-item label="价格" prop="price" required v-if="'2,3,4'.indexOf(globalVariable.userInfo.tbCommunity.type) === -1">
                <u-input v-model="validateForm.value.price" placeholder="请输入价格"/>
            </u-form-item>
            <u-form-item label="市场价" prop="marketPrice" required>
                <u-input v-model="validateForm.value.marketPrice" placeholder="请输入市场价"/>
            </u-form-item>
            <u-form-item label="库存数量" prop="stockNumber" required>
                <u-input v-model="validateForm.value.stockNumber" placeholder="请输入库存数量"/>
            </u-form-item>
            <u-form-item label="显示顺序" prop="displayOrder">
                <u-input v-model="validateForm.value.displayOrder" placeholder="请输入显示顺序（可选）"/>
            </u-form-item>

            <div v-if="'2,3,4'.indexOf(globalVariable.userInfo.tbCommunity.type) !== -1">
                <u-card :title="'客户类型价格'" :full="true">
                    <view class="" slot="body">
                        <u-form-item :label="item.name" :label-width="300" :prop="item.id" required v-for="(item, index) of tbCommunityUserTypeList"
                                     :key="item.id">
                            <u-input v-model="validateForm.value[item.id]" placeholder="请输入价格"/>
                        </u-form-item>
                    </view>
                </u-card>
            </div>
        </u-form>

        <u-button type="error" @click="submit">提交</u-button>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false" v-if="validateForm.controls.goodsSpecificationId.isShow"
                  v-model="validateForm.controls.goodsSpecificationId.isShow" :list="validateForm.controls.goodsSpecificationId.options"
                  :default-value="validateForm.controls.goodsSpecificationId.defaultValue"
                  @cancel="validateForm.controls.goodsSpecificationId.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.goodsSpecificationId)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false" v-if="validateForm.controls.goodsColorId.isShow"
                  v-model="validateForm.controls.goodsColorId.isShow" :list="validateForm.controls.goodsColorId.options"
                  :default-value="validateForm.controls.goodsColorId.defaultValue"
                  @cancel="validateForm.controls.goodsColorId.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.goodsColorId)"></u-select>
    </view>
</template>

<script>
    import {CommonService} from "@/dev/services/common.service";
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {TbGoodsSpecificationColorService} from "@/dev/services/tb-goods-specification-color.service";
    import {TbGoodsColorService} from "@/dev/services/tb-goods-color.service";
    import {TbGoodsSpecificationService} from "@/dev/services/tb-goods-specification.service";
    import {UFormUtil} from "@/dev/core/utils/u-form.util";
    import {TbCommunityUserTypeService} from "@/dev/services/tb-community-user-type.service";

    export default {
        data() {
            return {
                validateForm: {
                    value: {
                        id: CommonUtil.randomUUID(),
                        goodsId: null,
                        goodsSpecificationId: '',
                        goodsColorId: '',
                        costPrice: '',
                        price: '',
                        marketPrice: '',
                        stockNumber: '',
                        displayOrder: '',
                        tbGoodsSpecificationColorUserTypeList: [],
                    },
                    rules: {
                        goodsSpecificationId: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    const _self = this;
                                    if (value && this.validateForm.value.goodsColorId) {
                                        new CommonService().uniqueCheckByFields({
                                            "tableName": "tb_goods_specification_color",
                                            "fieldList": [
                                                {"fieldName": "goods_specification_id", "fieldValue": value},
                                                {"fieldName": "goods_color_id", "fieldValue": this.validateForm.value.goodsColorId}
                                            ],
                                            "excludeId": null
                                        }).then(result => {
                                            if (result.status === "fail") {
                                                callback(new Error('该颜色与该规格已关联！'));
                                            } else {
                                                callback();
                                                // 自动关联商品规格的价格和库存数量
                                                _self.validateForm.controls.goodsSpecificationId['options'].forEach(item => {
                                                    if (item.id === value) {
                                                        console.log("------------------------------", item);
                                                        _self.validateForm.value.price = item.price;
                                                        _self.validateForm.value.stockNumber = item.stockNumber;
                                                        _self.validateForm.value.marketPrice = item.marketPrice;
                                                    }
                                                });
                                            }
                                        })
                                    } else {
                                        callback();
                                    }
                                }
                            }
                        ],
                        goodsColorId: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    if (value && this.validateForm.value.goodsSpecificationId) {
                                        new CommonService().uniqueCheckByFields({
                                            "tableName": "tb_goods_specification_color",
                                            "fieldList": [
                                                {"fieldName": "goods_specification_id", "fieldValue": this.validateForm.value.goodsSpecificationId},
                                                {"fieldName": "goods_color_id", "fieldValue": value}
                                            ],
                                            "excludeId": null
                                        }).then(result => {
                                            if (result.status === "fail") {
                                                callback(new Error('该规格与该颜色已关联！'));
                                            } else {
                                                callback();
                                            }
                                        })
                                    } else {
                                        callback();
                                    }
                                }
                            }
                        ],
                        costPrice: [
                            {pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '请输入有效的价格!', trigger: ['change', 'blur']}
                        ],
                        price: [
                            {
                                trigger: ['change', 'blur'],
                                asyncValidator: (rule, value, callback) => {
                                    // 公司模式
                                    if ('2,3,4'.indexOf(this.globalVariable.userInfo.tbCommunity.type) !== -1) {
                                        callback()
                                    } else {
                                        if (!value) {
                                            callback(new Error('必填项！'));
                                            return false;
                                        }
                                        let reg = /^[0-9]+(.[0-9]{1,2})?$/;
                                        if (!reg.test(value)) {
                                            callback(new Error('请输入有效的价格！'));
                                            return false;
                                        }
                                        callback()
                                    }
                                }
                            }
                        ],
                        marketPrice: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '请输入有效的价格!', trigger: ['change', 'blur']}
                        ],
                        stockNumber: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^[0-9]*$/, message: '请输入有效的数量!', trigger: ['change', 'blur']}
                        ],
                        displayOrder: [
                            {
                                pattern: /^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
                                message: '请输入大于0的正数!',
                                trigger: ['change', 'blur']
                            }
                        ],
                    }
                },
                tbCommunityUserTypeList: []
            }
        },
        onReady() {
            const _self = this;
            this.validateForm.value.goodsId = this.urlParams.goodsId;
            new TbGoodsSpecificationService().findTbGoodsSpecificationList({
                goodsId: _self.validateForm.value.goodsId
            }).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.goodsSpecificationId, CommonUtil.objectAlias(result, {'id': 'code'}));

            });
            new TbGoodsColorService().findTbGoodsColorList({
                goodsId: _self.validateForm.value.goodsId
            }).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.goodsColorId, CommonUtil.objectAlias(result, {'id': 'code'}));
                _self.$forceUpdate();
            });

            if ('2,3,4'.indexOf(_self.globalVariable.userInfo.tbCommunity.type) !== -1) {
                new TbCommunityUserTypeService().findTbCommunityUserTypeList({
                    communityId: _self.globalVariable.userInfo.tbCommunity.id
                }).then(result => {
                    result.forEach(item => {
                        _self.validateForm.value[item.id] = '0';

                        _self.validateForm.rules[item.id] = [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^[0-9]+(.[0-9]{1,2})?$/, message: '请输入有效的价格!', trigger: ['change', 'blur']}
                        ];
                    });

                    _self.tbCommunityUserTypeList = result;
                    console.log(_self.validateForm);
                    _self.$refs.validateFormRef.setRules(_self.validateForm.rules);
                    _self.$forceUpdate()
                });
            }
        },
        methods: {
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定

                                    _self.validateForm.value.tbGoodsSpecificationColorUserTypeList = [];
                                    _self.tbCommunityUserTypeList.forEach(item => {
                                        _self.validateForm.value.tbGoodsSpecificationColorUserTypeList.push({
                                            goodsId: _self.validateForm.value.goodsId,
                                            goodsSpecificationColorId: _self.validateForm.value.id,
                                            communityUserTypeId: item.id,
                                            price: _self.validateForm.value[item.id],
                                        });
                                    });

                                    new TbGoodsSpecificationColorService().saveTbGoodsSpecificationColor(_self.validateForm.value).then(result => {
                                        CommonUtil.toastNavigateBack('保存成功').then(result => {
                                            setTimeout(() => {
                                                _self.objParams();
                                            }, 500);
                                        });
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
</style>
